const { Op } = require("sequelize");
const Goods = require("../model/goods.model");

class GoodsService{
    async createGoods(goods){
        const res = await Goods.create(goods)
        return res.dataValues;
    }

    async updateGoods(id, goods){
        const res = await Goods.update(goods, {where: {id}})
        return res[0]>0?true:false;
    }

    async removeGoods(id){
        const res = await Goods.destroy({where:{id}})
        return res >0?true:false;
    }

    async restoreGoods(id){
        const res = await Goods.restore({where:{id}})
        return res >0?true:false;
    }

    async findGoods(pageNum, pageSize, goods_name){
        //获取可能的查询参数
        const whereOpt = {};
        goods_name && Object.assign(whereOpt, { goods_name: { [Op.like]: `%${goods_name}%` } });
        //获取总数
        const count = await Goods.count({ where: whereOpt })
        //获取分页数据
        const offset = (pageNum - 1) * pageSize;
        const rows =await Goods.findAll({ where: whereOpt, offset: offset, limit: pageSize*1})
        return {
            pageNum: pageNum,
            pageSize: pageSize,
            total: count,
            list: rows
        }
    }

}

module.exports = new GoodsService()